import React, {useCallback, useEffect, useRef, useState} from "react"
import {
    addMarketDeliveryOrderItem,
    AddMarketDeliveryOrderItemRequest,
    auditMarketDeliveryOrder, clearMarketDeliveryOrderItems,
    deleteMarketDeliveryOrderItem,
    getMarketDeliveryOrderDetail,
    MarketDeliveryOrderDetail,
    MarketDeliveryOrderItem,
    updateMarketDeliveryOrderItemAmount
} from "../../apis/MarketDeliveryOrderApi";
import {Button, Col, Descriptions, InputNumber, Row, Space, theme} from "antd";
import {OffsetDateTime} from "@js-joda/core";
import {convertAntdTableToExcel, ExportedColumnProps} from "../../utils/AntdTableUtils";
import AuthorizationResource from "../../components/AuthorizationResource";
import {DeleteOutlined} from "@ant-design/icons";
import DataPageLayout from "../../components/DataPageLayout";
import ArrayUtils from "@zxy-cn/array-utils";
import dashboardPageStore from "../../store/DashboardPageStore";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import EditOrderItemRow from "../../components/EditOrderItemRow";
import {Link} from "react-router-dom";
import LoadableButton from "../../components/LoadableButton";
import {saveWorkbookTo} from "../../utils/FileSaver";
import GoodsTable from "../../components/GoodsTable";
import {addMarketOrderItem, MarketOrderItem} from "../../apis/MarketOrderApi";
import {getAllGoodsWithMarketInStore, GoodsWithMarketInStore} from "../../apis/GoodsApi";
import EditAmountAndUnitPopover from "../EditAmountAndUnitPopover";
import {useLiveQuery} from "dexie-react-hooks";
import {GoodsAmountAndUnitUseHistoryScope, myDatabase} from "../../database/MyDatabase";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";
import ConfirmPopover from "../ConfirmPopover";


export interface pageProps {
    id: number
}

const myPath = "markets/deliveryOrders/{id}"

const MarketDeliveryOrderDetailPage: React.FC<pageProps> = ({id}) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<MarketDeliveryOrderDetail>()
    const query = useCallback(() => {
        setLoading(true)
        getMarketDeliveryOrderDetail(id).then(response => {
            dashboardPageStore.setTitle(myPath.replace("{id}", id.toString()), response.data.market.name + "送货单")
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, [id,])

    useEffect(() => {
        query()
    }, [query]);

    let token = theme.useToken();
    let columnsRef = useRef<ExportedColumnProps<MarketOrderItem>[]>();
    let amountAndUnitHistories = useLiveQuery(()=>{
        return myDatabase.goodsAmountAndUnitUseHistory.where({
            scope: GoodsAmountAndUnitUseHistoryScope.MARKET_ORDER,
            resourceId: id,
        }).toArray()
    },[id]);
    return (
        <>
            <div style={{display: "flex", flexDirection: "column"}}>
                {!loading ? <Descriptions title={"订单明细"}>
                    <Descriptions.Item label={"卖场"}>{data?.market?.name}</Descriptions.Item>
                    {!!data?.createdDateTime && <Descriptions.Item
                        label={"开单时间"}>{data?.createdDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item>}
                    {!!data?.validatedDateTime ? <Descriptions.Item
                        label={"验收时间"}>{data.validatedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item> : undefined}
                    {!!data?.auditedDateTime ? <Descriptions.Item
                        label={"审核时间"}>{data.auditedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item> : undefined}
                    <Descriptions.Item label={"编号"}>{data?.number}</Descriptions.Item>
                </Descriptions> : null}
                <Row gutter={8} style={{margin: "12px 0"}}>
                    <Col>
                        <LoadableButton onClick={async _ => {
                            let workbook = await convertAntdTableToExcel(columnsRef.current!, data?.items ?? []);
                            await saveWorkbookTo(workbook, `${data?.market?.name}送货单 ${data!.createdDateTime.format(DATE_WITH_TIME_FORMATER)}`)
                        }}>导出</LoadableButton>
                    </Col>
                    <Col>
                        {employeeAuthorizationStore.hasAuthority("卖场_送货单_修改") && !data?.validatedDateTime && <ConfirmPopover onConfirm={async ()=>{
                            await clearMarketDeliveryOrderItems(id)
                            setData({
                                ...data!!,
                                items:[]
                            })
                        }} description={"是否要清空此送货单"}/>}
                    </Col>
                    {employeeAuthorizationStore.hasAuthority("卖场_送货单_审核") && !data?.auditedDateTime &&
                        !!data?.validatedDateTime &&
                        <LoadableButton type={"primary"} onClick={async () => {
                            await auditMarketDeliveryOrder(id)
                            setData({...data!, auditedDateTime: OffsetDateTime.now()})
                        }}>审核订单</LoadableButton>}
                    <div style={{flexGrow: 1}}/>
                    {
                        !!data?.hasDifference && employeeAuthorizationStore.hasAllAuthority("卖场_订单_查询", "卖场_送货单_查询") &&
                        <Link to={`/markets/deliveryOrders/${id}/compareWithOriginalOrder`}>
                            <Button type={"link"}>查看与原订单差异</Button>
                        </Link>
                    }

                    <Link to={`/markets/orders/${id}`}>
                        <Button type={"link"}>原订单</Button>
                    </Link>
                </Row>

                {employeeAuthorizationStore.hasAuthority("卖场_送货单_修改") && !data?.auditedDateTime &&
                    !!data &&
                    <EditOrderItemRow< GoodsWithMarketInStore>
                        request={{editMarketOrderId: id}}
                        fetchGoods={() =>
                            getAllGoodsWithMarketInStore(data.market.id).then(res => {
                                return res.data
                            })}
                        optionRender={it => <div style={{display: 'flex', flexDirection: "column"}}>
                            <div style={{display: "flex", justifyContent: 'space-between'}}>
                                <span>{it.barcode}</span><span>{it.name}</span>
                            </div>
                            <Space
                                size={24}><span>卖场存货:{it.amountInMarket ?? "无"}</span><span>库存:{it.amount}</span></Space>
                        </div>}
                        onFinish={async (values) => {
                            let existed = amountAndUnitHistories?.find(it=>it.goodsId===values.goodsId);
                            if(existed){
                                myDatabase.goodsAmountAndUnitUseHistory.delete(existed.id!!)
                            }
                            myDatabase.goodsAmountAndUnitUseHistory.add({
                                scope:GoodsAmountAndUnitUseHistoryScope.MARKET_ORDER,
                                resourceId:id,
                                amount:values.amount,
                                unitId:values.unitId,
                                goodsId:values.goodsId
                            })
                            return addMarketDeliveryOrderItem(id, values).then(() => {
                                query()
                            })
                        }}
                        availableAmountAndUnitHistories={amountAndUnitHistories}
                        existedGoodsKeys={data?.items?.map(it => ({
                            /*TODO*/
                            goodsId:it.id,
                        })) ?? []}/>}
                <DataPageLayout leftActions={<>
                </>}>

                    <GoodsTable<MarketDeliveryOrderItem> loading={loading}
                                                         data={data?.items ?? []}
                                                         size={"small"}
                                                         customColumns={columns => {
                                                             ArrayUtils.insertAfter(columns, value => value.dataIndex === "name", {
                                                                 dataIndex: "amountInOrder",
                                                                 title: "数量",
                                                                 render: (value, record) => {
                                                                     return <div>{value}{record.unit?.name}</div>
                                                                 }
                                                             },)
                                                             columns.push({
                                                                 ignoreInExcel: true,
                                                                 title: "操作",
                                                                 render: (_, item, __) => {
                                                                     return <>
                                                                         {(employeeAuthorizationStore.hasAuthority("卖场_订单_转化为送货单") || employeeAuthorizationStore.hasAuthority(
                                                                                 "卖场_送货单_修改"
                                                                             )) && !data?.auditedDateTime &&
                                                                             <EditAmountAndUnitPopover
                                                                                 units={item.units}
                                                                                 onConfirm={async value => {
                                                                                     await updateMarketDeliveryOrderItemAmount(id, item.id, {
                                                                                         amount: value.amount,
                                                                                         unitId: value.unitId
                                                                                     })
                                                                                     let items = Array.from(data?.items ?? []);
                                                                                     let index = data?.items.findIndex(it => it.id === item.id)!!;
                                                                                     let item1 = items[index];
                                                                                     let unit = item.units.find(it => it.id === value.unitId);
                                                                                     item1.unit = unit
                                                                                     item1.amount -= (value.amount * (unit?.basicMultiple ?? 1)) - item1.amountInOrder
                                                                                     item1.amountInOrder = value.amount
                                                                                     setData({
                                                                                         ...data!,
                                                                                         items
                                                                                     })
                                                                                 }}
                                                                                 initialData={{
                                                                                     amount: item.amountInOrder,
                                                                                     unitId: item.unit?.id
                                                                                 }}>
                                                                                 <Button type={"link"}
                                                                                         onClick={(event) => {
                                                                                             event.stopPropagation()
                                                                                         }}>修改数量</Button>
                                                                             </EditAmountAndUnitPopover>}

                                                                         <AuthorizationResource
                                                                             authorities={["卖场_送货单_修改"]}>
                                                                             <Button type={"link"}
                                                                                     danger
                                                                                     onClick={(event) => {
                                                                                         event.stopPropagation()
                                                                                         deleteMarketDeliveryOrderItem(id, item.id).then(() => {
                                                                                             let items = Array.from(data!.items);
                                                                                             ArrayUtils.remove(items, item)
                                                                                             setData({
                                                                                                 ...data!,
                                                                                                 items
                                                                                             })
                                                                                         })
                                                                                     }}>
                                                                                 <DeleteOutlined/>
                                                                                 删除
                                                                             </Button>
                                                                         </AuthorizationResource>
                                                                     </>
                                                                 }
                                                             },);
                                                             columnsRef.current = columns;
                                                             return columns;
                                                         }}
                                                         rowKey={"id"}>
                    </GoodsTable>|
                </DataPageLayout></div>

        </>
    )
}

export default observerDashboardPageWrapper(MarketDeliveryOrderDetailPage, myPath, "卖场送货单详情")

